package com.cll.pmis.controller;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.cll.pmis.common.PageInfo;
import com.cll.pmis.common.Result;
import com.cll.pmis.common.annotation.HasPerms;
import com.cll.pmis.common.annotation.HasRoles;
import com.cll.pmis.common.security.SysUser;
import com.cll.pmis.common.utils.CommonUtil;
import com.cll.pmis.common.validator.ValidatorUtils;
import com.cll.pmis.common.validator.group.Insert;
import com.cll.pmis.common.validator.group.Update;
import com.cll.pmis.entity.Drug;
import com.cll.pmis.service.IDrugService;
import io.github.llchen.apidoc.DataType;
import io.github.llchen.apidoc.annotation.Api;
import io.github.llchen.apidoc.annotation.ApiDoc;
import io.github.llchen.apidoc.annotation.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 药品管理
 * </p>
 *
 * @author chenliangliang
 * @since 2018-06-18
 */
@ApiDoc(name = "药品api",description = "药品相关接口api")
@RestController
@RequestMapping("/drug")
public class DrugController {

    private IDrugService drugService;

    protected DrugController(IDrugService drugService) {
        this.drugService = drugService;
    }

    @HasRoles("admin")
    @GetMapping("/test")
    public Result test(SysUser user) {
        return Result.ok(user);
    }


    @HasPerms("drug:insert")
    @PostMapping("/add")
    public Result addDrug(@RequestBody Drug drug) {
        ValidatorUtils.validateEntity(drug, Insert.class);
        drug.setCreateTime(new Date());
        drug.setUpdateTime(new Date());
        drugService.insert(drug);
        return Result.ok(drug);
    }

    @HasPerms("drug:update")
    @PostMapping("/update")
    public Result updateDrug(@RequestBody Drug drug) {
        ValidatorUtils.validateEntity(drug, Update.class);
        drug.setUpdateTime(new Date());
        return drugService.updateById(drug) ? Result.ok(drug) : Result.updateError();
    }


    @HasPerms("drug:delete")
    @PostMapping("/delete")
    public Result deleteDrug(@Param("drugId") Integer drugId) {
        return drugService.deleteById(drugId) ? Result.ok("") : Result.deleteError();
    }


    @GetMapping("/query")
    public Result getDrugName(@RequestParam(value = "q") String drugName){

        if (StringUtils.isEmpty(drugName)){
            drugName="";
        }

        List<Map<String, Object>> mapList = drugService.getMapper().queryDrugName("%"+drugName+"%");

        return Result.ok(mapList);
    }


    @HasPerms("drug:select")
    @GetMapping("/select")
    public Result queryDrug(@RequestParam(value = "id") Integer id) {
        if (id==null){
            return Result.paramError();
        }
        Drug drug = drugService.selectById(id);
        return Result.ok(drug);
    }


    /**
     * 药房取药信息
     */
    @Api(description = "药房取药信息",requestParams = {
            @ApiParam(name = "pageIndex",description = "页码",required = false,defaultValue = "1",type = DataType.INT),
            @ApiParam(name = "pageSize",defaultValue = "4",description = "每页数据量",required = false,type = DataType.INT),
            @ApiParam(name = "time",description = "时间过滤,可以不填，则匹配所有",example = "2018-02-08 12:05:16"),
            @ApiParam(name = "query",description = "可填:用户名，手机号码，病例号"),
            @ApiParam(name = "status",description = "状态:0->未支付,1->已支付",type = DataType.INT)
    },demoResponse = "",
    responseParams = {
            @ApiParam(name = "dossierId",description = "病例号"),
            @ApiParam(name = "username",description = "病人姓名"),
            @ApiParam(name = "age",description = "病人年龄"),
            @ApiParam(name = "sex",description = "病人姓别"),
            @ApiParam(name = "summary",description = "开的药品名"),
            @ApiParam(name = "orderStatus",description = "订单状态：0->未支付，1->已支付",type = DataType.INT),
            @ApiParam(name = "outputStatus",description = "出库状态：0->不可用，1->待审核，2->审核通过",type = DataType.INT),
            @ApiParam(name = "doctor",description = "开药的医生"),
            @ApiParam(name = "updateTime",description = "时间"),
    })
    @HasPerms("drug:take")
    @GetMapping("/take")
    public Result drugTake(@RequestParam(value = "pageIndex", required = false) Integer pageIndex,
                           @RequestParam(value = "pageSize", required = false) Integer pageSize,
                           @RequestParam(value = "time", required = false) String time,
                           @RequestParam(value = "query", required = false) String query,
                           @RequestParam(value = "status", required = false) Integer status) {

        if (pageIndex == null || pageIndex < 1) {
            pageIndex = 1;
        }

        if (pageSize == null || pageSize < 1) {
            pageSize = 4;
        }

        String dateTime = null;
        if (StringUtils.isNotEmpty(time)) {
            Date date = CommonUtil.parseDate(time);
            if ( date!= null){
                dateTime = CommonUtil.formatDate(date);
            }else {
                return Result.fail("日期格式错误");
            }
        }

        String username = null;
        String phone = null;
        Integer dossierId = null;

        if (StringUtils.isNotEmpty(query)) {
            if (CommonUtil.isPhone(query)) {
                phone = query;
            } else if (CommonUtil.isNumber(query)) {
                dossierId = Integer.valueOf(query);
            } else {
                username = query;
            }
        }

        PageInfo<Map<String, Object>> pageInfo = drugService.getDrugTakeInfo(pageIndex, pageSize, dateTime, username, phone, dossierId, status);

        return Result.ok(pageInfo);
    }


    @GetMapping("/company")
    public Result listCompany(@RequestParam("q") String query){
        if (query==null){
            query="";
        }
        query=query+"%";
        List<String> list = drugService.getMapper().listCompany(query);
        return Result.ok(list);
    }


    @GetMapping("/list")
    public Result list(@RequestParam(value = "pageIndex", required = false) Integer pageIndex,
                       @RequestParam(value = "pageSize", required = false) Integer pageSize,
                       @RequestParam(value = "name", required = false) String name) {

        if (pageIndex == null || pageIndex < 1) {
            pageIndex = 1;
        }

        if (pageSize == null || pageSize < 1) {
            pageSize = 4;
        }


        Page<Drug> page = drugService.selectPage(new Page<>(pageIndex, pageSize,"id",false),
                new EntityWrapper<Drug>().like(StringUtils.isNotEmpty(name), "name", name));
        return Result.ok(page);
    }

}

